#!/bin/bash
### BEGIN INIT INFO
# Provides:          cloudstack-agent
# Required-Start:    $network 
# Required-Stop:     $network 
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# X-Interactive:     true
# Short-Description: Start/stop apache2 web server
### END INIT INFO

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well

. /lib/lsb/init-functions
. /etc/rc.status

# set environment variables

SHORTNAME=`basename $0`
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="Cloud Agent"
CLASS="com.cloud.agent.AgentShell"

unset OPTIONS
[ -r @SYSCONFDIR@/default/"$SHORTNAME" ] && source @SYSCONFDIR@/default/"$SHORTNAME"

# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm"

for jdir in $JDK_DIRS; do
    if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
        JAVA_HOME="$jdir"
    fi
done
export JAVA_HOME

SCP="@SYSTEMCLASSPATH@"
DCP="@DEPSCLASSPATH@"
ACP="@AGENTCLASSPATH@"
JCP="/usr/share/java/commons-daemon.jar"

# We need to append the JSVC daemon JAR to the classpath
# AgentShell implements the JSVC daemon methods
export CLASSPATH="$SCP:$DCP:$ACP:$JCP:@AGENTSYSCONFDIR@"

wait_for_network() {
    i=1
    while [ $i -lt 10 ]
    do
        # Under Ubuntu and Debian libvirt by default creates a bridge called virbr0.
        # That's why we want more then 3 lines back from brctl, so that there is a manually created bridge
        if [ "$(brctl show|wc -l)" -gt 2 ]; then
            break
        else
            sleep 1
            let i=$i+1
            continue
        fi
    done
}

start() {
        log_daemon_msg $"Starting $PROGNAME" "$SHORTNAME"
	if [ -s "$PIDFILE" ] && kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
	      log_progress_msg "apparently already running"
	      log_end_msg 0
	      exit 0
	fi
	if hostname --fqdn >/dev/null 2>&1 ; then
		true
	else
		log_failure_msg "The host name does not resolve properly to an IP address.  Cannot start $PROGNAME"
		log_end_msg 1
		exit 1
	fi

        wait_for_network

	if jsvc -cp "$CLASSPATH" -pidfile "$PIDFILE" -errfile SYSLOG $CLASS
		RETVAL=$?
	    then
		rc=0
		sleep 1
		if ! kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
		    log_failure_msg "$PROG failed to start"
		    rc=1
		fi
	else
		rc=1
	fi

	if [ $rc -eq 0 ]; then
		log_end_msg 0
	else
		log_end_msg 1
		rm -f "$PIDFILE"
	fi
}

stop() {
    SHUTDOWN_WAIT="30"
    count="0"

    echo -n $"Stopping $PROGNAME" "$SHORTNAME"
    jsvc -pidfile "$PIDFILE" -stop $CLASS

    until [ "$count" -gt "$SHUTDOWN_WAIT" ]
    do
        agentPid=`ps aux|grep [j]svc|grep cloud-agent`
        if [ "$?" -gt "0" ];then
            break
        fi
        sleep 1
        let count="${count}+1"
    done

    agentPid=`ps aux|grep [j]svc|grep cloud-agent`
    if [ "$?" -eq "0" ]; then
         agentPid=`ps aux|grep [j]svc|awk '{print $2}'`
         if [ "$agentPid" != "" ]; then
              kill -9 $agentPid
         fi
    fi

    log_end_msg $?
    rm -f "$PIDFILE"
}


# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
        status_of_proc -p "$PIDFILE" "$PROG" "$SHORTNAME"
	RETVAL=$?
	;;
  restart)
	stop
	sleep 3
	start
	;;
  *)
	echo $"Usage: $SHORTNAME {start|stop|restart|status|help}"
	RETVAL=3
esac

exit $RETVAL

